package com.runvp.common.hex;

public class BinaryTypeConvert {
    /*
 * 字符转换为字节
 */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    /*
     * 16进制字符串转字节数组
     */
    public static byte[] hexString2Bytes(String hex) {

        if ((hex == null) || (hex.equals(""))){
            return null;
        }
        else if (hex.length()%2 != 0){
            return null;
        }
        else{
            hex = hex.toUpperCase();
            int len = hex.length()/2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i=0; i<len; i++){
                int p=2*i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
            }
            return b;
        }

    }
    /*
     * 字节数组转字符串
     */
    public static String bytes2String(byte[] b) throws Exception {
        String r = new String (b,"UTF-8");
        return r;
    }
    /*
      * 16进制字符串转字符串
      */
    public static String hex2String(String hex, int i) throws Exception{
        String r = bytes2String(hexString2Bytes(hex));
        return r;
    }
    /*
     * 字符串转16进制字符串
     */
    public static String string2HexString(String s) throws Exception{
        String r = bytes2HexString(string2Bytes(s));
        return r;
    }

    /*
     * 字节数组转16进制字符串
     */
    public static String bytes2HexString(byte[] b) {
        String r = "";

        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            r += hex.toUpperCase();
        }

        return r;
    }
    /*
    * 字符串转字节数组
    */
    public static byte[] string2Bytes(String s){
        byte[] r = s.getBytes();
        return r;
    }



    public static void main(String[] args) throws Exception {
        String source = "DSTLIIP<   \u0007?LHY";
        System.out.println("原始数据："+source);
        String str =  string2HexString(source);
        System.out.println("字符串10进制转16进制:"+str);
        str =  hex2String("0x44",16);
        System.out.println("字符串16进制转10进制:"+str);
//        DSTLIIP<   ?LHY
        byte [] b;
        String utf8_value ="DSTLIIP<   ?LHY";
        b = utf8_value.getBytes("8859_1"); //中间用ISO-8859-1过渡
        String name = new String(b, "GB2312"); //转换成GB2312字符。
        System.out.println(name);
        String input = "0x07";
        int out = Integer.parseInt(input.substring(2, input.length()), 16);
        System.out.println(out);
    }
}
